package com.example.rate;

import static androidx.core.app.ActivityCompat.startActivityForResult;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MainActivity extends AppCompatActivity {
    private static final int REQUEST_EDIT_RATES = 1;
    private double usdRate = 6.5;
    private double eurRate = 7.5;
    private double jpyRate = 0.06;
    private SharedPreferences prefs;
    private static final String RATE_URL = "http://www.boc.cn/sourcedb/whpj/";
    private ProgressDialog loadingDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button btnRefresh = findViewById(R.id.btn_refresh);
        btnRefresh.setOnClickListener(v -> fetchRates());

        EditText inputCny = findViewById(R.id.input_cny);
        Button btnEdit = findViewById(R.id.btn_edit_rates);

        prefs = getSharedPreferences("exchange_rates", MODE_PRIVATE);
        loadSavedRates();

        private void loadSavedRates() {
            usdRate = prefs.getFloat("usd_rate", 6.5f);
            eurRate = prefs.getFloat("eur_rate", 7.5f);
            jpyRate = prefs.getFloat("jpy_rate", 0.06f);
        }

        private void saveRates() {
            prefs.edit()
                    .putFloat("usd_rate", (float) usdRate)
                    .putFloat("eur_rate", (float) eurRate)
                    .putFloat("jpy_rate", (float) jpyRate)
                    .apply();
        }

        // 实时计算监听
        inputCny.addTextChangedListener(new TextWatcher() {
            @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override public void onTextChanged(CharSequence s, int start, int before, int count) {}

            @Override
            public void afterTextChanged(Editable s) {
                calculate(s.toString());
            }
        });

        // 跳转修改页面
        btnEdit.setOnClickListener(v -> {
            Intent intent = new Intent(MainActivity.this, EditRateActivity.class);
            intent.putExtra("USD_RATE", usdRate);
            intent.putExtra("EUR_RATE", eurRate);
            intent.putExtra("JPY_RATE", jpyRate);
            startActivityForResult(intent, REQUEST_EDIT_RATES);
        });
    }

    private void loadSavedRates() {
    }

    private void calculate(String input) {
        if (input.isEmpty()) return;
        try {
            double cny = Double.parseDouble(input);
            updateResult(R.id.result_usd, cny / usdRate, "美元：");
            updateResult(R.id.result_eur, cny / eurRate, "欧元：");
            updateResult(R.id.result_jpy, cny / jpyRate, "日元：");
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    private void updateResult(int viewId, double value, String prefix) {
        ((TextView) findViewById(viewId)).setText(
                String.format(prefix + "%.2f", value)
        );
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_EDIT_RATES && resultCode == RESULT_OK && data != null) {
            usdRate = data.getDoubleExtra("NEW_USD_RATE", usdRate);
            eurRate = data.getDoubleExtra("NEW_EUR_RATE", eurRate);
            jpyRate = data.getDoubleExtra("NEW_JPY_RATE", jpyRate);
            calculate(((EditText) findViewById(R.id.input_cny)).getText().toString());
        }
    }

    private void fetchRates() {
        loadingDialog = ProgressDialog.show(this, "", "正在获取汇率...", true);

        NetworkUtil.getHtmlAsync(RATE_URL, new NetworkUtil.Callback() {
            @Override
            public void onSuccess(String result) {
                parseHtml(result);
                loadingDialog.dismiss();
            }

            @Override
            public void onFailure(Exception e) {
                runOnUiThread(() -> {
                    loadingDialog.dismiss();
                    Toast.makeText(MainActivity.this, "获取失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
                });
            }
        });
    }

    private void parseHtml(String html) {
        try {
            // 这里需要根据实际网页结构编写解析逻辑
            // 示例正则匹配（以中国银行外汇牌价为例）
            Pattern usdPattern = Pattern.compile("美元</td>\\s*<td>[\\d.]+</td>\\s*<td>[\\d.]+</td>\\s*<td>([\\d.]+)");
            Matcher matcher = usdPattern.matcher(html);
            if (matcher.find()) {
                usdRate = Double.parseDouble(matcher.group(1));
            }
            // 同理解析其他货币
            runOnUiThread(() -> calculate(inputCny.getText().toString()));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void runOnUiThread(Object o) {
    }
}

